package cn.lixin.org.controller;

import cn.lixin.basic.utils.AjaxResult;
import cn.lixin.basic.utils.FastDfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传文件
 */
@RequestMapping("/fastDfs")
@RestController
@Api(tags = "文件上传接口",description = "件上传接口详细描述")
public class FastDfsController {

    /**
     * RequestPart:文件上传必需
     * @param file
     * @return
     */
    @PostMapping
    @ApiOperation(value = "文件上传",notes = "文件上传")
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){// upload(byte[] file,String extName)
        try {
            String originalFilename = file.getOriginalFilename();// 获取原始文件路径 ----333.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); // 后缀extName
            String filePath = FastDfsUtil.upload(file.getBytes(), extName);
            return new AjaxResult().setResultObj(filePath).setSuccess(true).setMessage("上传成功"); // 将文件路径返回给前端

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setMessage("上传失败").setSuccess(false);
        }

    }

    /**
     * RequestParam:
     * @param path
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "文件删除",notes = "文件删除")
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){//  delete(String groupName,String fileName)
        try {
            // path: /group1/M00/00/55/rBE3kWDa5cuAYlSsAAuUuyjIsMY302.jpg
            String path1 = path.substring(1); // 把第一个斜杠去除 group1/M00/00/55/rBE3kWDa5cuAYlSsAAuUuyjIsMY302.jpg
            String groupName = path1.substring(0,path1.indexOf("/")); // 从0开始，到第一个 / 结束
            String fileName = path1.substring(path1.indexOf("/")+1);
            FastDfsUtil.delete(groupName,fileName);// group1===M00/00/55/rBE3kWDa5cuAYlSsAAuUuyjIsMY302.jpg
            return new AjaxResult().setSuccess(true).setMessage("删除成功"); // 将文件路径返回给前端
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setMessage("删除失败"+e.getMessage()).setSuccess(false);
        }

    }

}
